/**
 * Created by qiushaohua on 14-4-21.
 */
define(["app",
    "jquery",
    "angular",
    "websocket",
    "services/UserService"
], function (app, $, angular, websocket) {

    var FLAGS = "Conversation";

    var deps = ['$rootScope', "UserService"];

    function service($rootScope, UserService) {

        var socket, // 这里改为一个Socket 处理所有的信息了
            loginUser,
            isInit = false;

        function onMessage(resp) {
    		// 根据消息中的flag 来进行处理了.
            var listenFlag = resp.listenFlag;

            $rootScope.$bus.publish({
                channel: 'websocket',
                topic: listenFlag,
                data: resp
            });
    	}
        
        function onReconn() {
            $rootScope.$bus.publish({
                channel: 'websocket.event',
                topic: 'reconnect',
                data: {}
            });
    	}
        
        function closeSocket() {
            if (socket) {
                socket();
                socket = null;
                $rootScope.$bus.publish({
                    channel: 'websocket.event',
                    topic: 'close',
                    data: {}
                });
            }
        }

        function doInit() {
            loginUser = UserService.getCurrentUser();
            if (loginUser == null) {
                // 可能还没有登录, 结果就没有用户信息了
                return;
            }
            isInit = true;
        }

        return {
            open: function () {
                if (!isInit) {
                    doInit();
                }
                if (loginUser == null) {
                    // 可能还没有登录, 结果就没有用户信息了
                    isInit = false;
                    return;
                }
                if (socket == null) {
                    socket = websocket.openMsgPush(loginUser.userId, loginUser.userName, loginUser.password, FLAGS, onMessage, onReconn);
                    $rootScope.$bus.publish({
                        channel: 'websocket.event',
                        topic: 'connect',
                        data: {}
                    });
                }
            },
            destroy: function() {
                // 关闭WebSocket.
                closeSocket();
                loginUser = null;
                isInit = false;
            }
        };
    }

    service.$inject = deps;
    app.lazy.service("WebsocketService", service);
});
